﻿$(function () {

    /***********创建数据库****************************************************/
    InitializeDatabase();
    /***************************************************************/
    /*登录*/
    $("#btnLogin").click(function () {
        var username = document.getElementById("username").value;
        var password = document.getElementById("password").value;
        var b = verify(username, password);
        if (b)
            loginSys(username, password);
    });

});

/*初始化数据库*/
function InitializeDatabase() {
    var db = window.openDatabase("SugarDB", "1.0", "SugarDB", 5000000);
    db.transaction(DoCreateDataTable, errorCB);
}
function DoCreateDataTable(tx) {
    //检查LoginInfo表是否存在
    var CheckDataVersionTableExistsSql = "SELECT count(*) AS cnt FROM sqlite_master WHERE type='table' AND name='LoginInfo';";
    tx.executeSql(CheckDataVersionTableExistsSql, [], querySuccess, errorCB);

}
function querySuccess(tx, results) {
    var tablecount = results.rows.item(0).cnt;
    //判断是否存在表
    if (tablecount <= 0) {
        //创建数据登录用户信息表
        var CreateDataTableUserSql = "create table if not exists LoginInfo (id integer not null primary key ,loginName text,password text,details text,createtime text,sex integer)";
        tx.executeSql(CreateDataTableUserSql);
        //插入初始数据
        //        var InsertDataTableUserSql = "insert into  LoginInfo (id,loginName,password,details) values(1,'admin','admin','')";
        //        tx.executeSql(InsertDataTableUserSql);
        alert("创建数据表");
    }
}

function errorCB(err) {
    console.log("错误处理的SQL：" + err.code + "错误信息：" + err.message);
    alert("错误信息：" + err.message);
}

// 事务执行成功后调用的回调函数
function successCB() {
    alert("创建成功！");
}

/*验证*/
function verify(username, password) {
    if (username == "") {
        alert("请输入帐号！");
        return false;
    }
    if (password == "") {
        alert("请输入密码！");
        return false;
    }
    return true;
}
//登陆操作 
function loginSys(username, password) {
    $.ajax({
        type: "POST",
        dataType: "text",
        //cache:true,
        url: "ashx/LoginHandler.ashx?action=Login",
        data: { username: username, password: password },
        success: function (status) {
            if (status == "0") {
                window.location.href = "index.html";
            }
            else {
                alert('账号或密码错误!');
            }
        },
        error: function (err) {
            alert(err.responseTest);
            alert('获取账号信息失败...请联系管理员!');
        }
    });
}

